package com.bx.implatform.kafka.service;

import com.alibaba.fastjson.JSON;
import com.bx.imclient.IMClient;
import com.bx.imcommon.enums.IMTerminalType;
import com.bx.imcommon.model.IMSystemMessage;
import com.bx.implatform.growUp.entity.EventEfficiency;
import com.bx.implatform.growUp.param.GetEventListParam;
import com.bx.implatform.growUp.service.GrowUpApiService;
import com.bx.implatform.kafka.entity.EventScreenNotice;
import com.bx.implatform.kafka.mapper.CDNoticeMsgMapper;
import com.bx.implatform.kafka.mapper.CDNoticeMsgRouteMapper;
import com.bx.implatform.kafka.mapper.CDNoticeMsgUserMapper;
import com.bx.implatform.util.GpsCoordinateUtils;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class KafKaService {

    private final IMClient imClient;
    private final CDNoticeMsgMapper noticeMsgMapper;
    private final CDNoticeMsgUserMapper noticeMsgUserMapper;
    private final CDNoticeMsgRouteMapper noticeMsgRouteMapper;
    private final GrowUpApiService growUpApiService;

    // /**
    //  * 4.1新增事件通知
    //  *
    //  * @param message
    //  * @param ack
    //  */
    // @KafkaListener(topics = "newevent")
    // public void newevent(@Payload String message, Acknowledgment ack) {
    //     // 新增事件通知
    //     try {
    //         System.out.println("Received new event notification: " + message);
    //         NewEvent newEvent = JSON.parseObject(message, NewEvent.class);
    //         // 这里添加您的业务逻辑，如通知APP用户等
    //         // TODO 根据路段查询部门ID，根据id查询人员列表
    //         String roadId = newEvent.getRoadId();
    //         List<String> userList = new ArrayList<>();
    //
    //         CDNoticeMsg msg = new CDNoticeMsg();
    //         msg.setEventId(newEvent.getId());
    //         msg.setNoticeType("1");
    //         msg.setNoticeLeve(newEvent.getEmergencyEvent());
    //         msg.setSource(newEvent.getSource());
    //         msg.setEventType(newEvent.getEventType());
    //         msg.setEventCategory(newEvent.getEventCategory());
    //         msg.setAlarmTime(newEvent.getAlarmTime());
    //         msg.setRoadId(newEvent.getRoadId());
    //         msg.setArea(newEvent.getArea());
    //         msg.setBeginPosition(newEvent.getBeginPosition());
    //         msg.setEndPosition(newEvent.getEndPosition());
    //         msg.setLongitude(newEvent.getLongitude());
    //         msg.setLatitude(newEvent.getLatitude());
    //         msg.setEventOverview(null);
    //         msg.setEventDescription(newEvent.getEventDescription());
    //         msg.setUserIds(userList.toString());
    //         msg.setInjureAmount(newEvent.getInjureAmount());
    //         msg.setDeathMount(newEvent.getDeathAmount());
    //         msg.setAlarmId(newEvent.getAlarmId());
    //         msg.setPlanName(null);
    //         msg.setPlanUrl(null);
    //         msg.setPushTime(new Date().toString());
    //         noticeMsgMapper.insert(msg);
    //         if (!userList.isEmpty()) {
    //             userList.forEach(userId -> {
    //                 CDNoticeMsgUser noticeMsgUser = new CDNoticeMsgUser();
    //                 noticeMsgUser.setNoticeId(msg.getNoticeId());
    //                 noticeMsgUser.setUserId(userId);
    //                 noticeMsgUser.setState(0);
    //                 noticeMsgUser.setNoticeType("1");
    //                 noticeMsgUserMapper.insert(noticeMsgUser);
    //             });
    //         }
    //         ack.acknowledge();
    //     } catch (Exception e) {
    //         // 添加适当的异常处理
    //         System.err.println("Error processing newevent message: " + e.getMessage());
    //         // 根据业务需求决定是否ack或采取其他措施
    //     }
    // }
    //
    // /**
    //  * 4.2 事件一键启动通知下发
    //  *
    //  * @param message
    //  * @param ack
    //  */
    // @KafkaListener(topics = "emergencyrecord", groupId = "my-group")
    // public void emergencyrecord(@Payload String message, Acknowledgment ack) {
    //     // 事件一键启动通知下发
    //     try {
    //         System.out.println("Received new event notification: " + message);
    //         EmergencyRecord emergencyRecord = JSON.parseObject(message, EmergencyRecord.class);
    //         // 这里添加您的业务逻辑，如通知APP用户等
    //         CDNoticeMsg msg = new CDNoticeMsg();
    //         msg.setNoticeType("2");
    //         msg.setEventId(emergencyRecord.getEventId());
    //         msg.setUserIds(emergencyRecord.getUserIds().toString());
    //         msg.setEventDescription(emergencyRecord.getSuggestion());
    //         msg.setPlanName(emergencyRecord.getPlanName());
    //         msg.setPlanUrl(emergencyRecord.getPlanUrl());
    //         msg.setSource(emergencyRecord.getCreateBy());
    //         msg.setEventOverview(emergencyRecord.getEventOverview());
    //         msg.setAlarmTime(emergencyRecord.getCreateTime());
    //         msg.setPushTime(new Date().toString());
    //         noticeMsgMapper.insert(msg);
    //         List<String> userList = emergencyRecord.getUserIds();
    //         if (!userList.isEmpty()) {
    //             userList.forEach(userId -> {
    //                 CDNoticeMsgUser noticeMsgUser = new CDNoticeMsgUser();
    //                 noticeMsgUser.setNoticeId(msg.getNoticeId());
    //                 noticeMsgUser.setUserId(userId);
    //                 noticeMsgUser.setState(0);
    //                 noticeMsgUser.setNoticeType("2");
    //                 noticeMsgUserMapper.insert(noticeMsgUser);
    //             });
    //         }
    //         ack.acknowledge();
    //     } catch (Exception e) {
    //         // 添加适当的异常处理
    //         System.err.println("Error processing newevent message: " + e.getMessage());
    //         // 根据业务需求决定是否ack或采取其他措施
    //     }
    // }
    //
    // /**
    //  * 4.3事件处置卡下发
    //  *
    //  * @param message
    //  * @param ack
    //  */
    // @KafkaListener(topics = "emergencytask", groupId = "my-group")
    // public void emergencytask(@Payload String message, Acknowledgment ack) {
    //     // 事件处置卡下发
    //     try {
    //         System.out.println("Received new event notification: " + message);
    //         EmergencyTask emergencyTask = JSON.parseObject(message, EmergencyTask.class);
    //         // 这里添加您的业务逻辑，如通知APP用户等
    //         ack.acknowledge();
    //     } catch (Exception e) {
    //         // 添加适当的异常处理
    //         System.err.println("Error processing newevent message: " + e.getMessage());
    //         // 根据业务需求决定是否ack或采取其他措施
    //     }
    // }
    //
    // /**
    //  * 4.4事件分流方案下发
    //  *
    //  * @param message
    //  * @param ack
    //  */
    // @KafkaListener(topics = "eventdivideplan", groupId = "my-group")
    // public void eventdivideplan(@Payload String message, Acknowledgment ack) {
    //     // 事件分流方案下发
    //     try {
    //         System.out.println("Received new event notification: " + message);
    //         EventDividePlan eventDividePlan = JSON.parseObject(message, EventDividePlan.class);
    //         // 这里添加您的业务逻辑，如通知APP用户等
    //         CDNoticeMsg msg = new CDNoticeMsg();
    //         msg.setNoticeType("3");
    //         msg.setEventId(eventDividePlan.getEventId());
    //         msg.setUserIds(eventDividePlan.getUserIds().toString());
    //         msg.setAlarmTime(eventDividePlan.getCreateTime());
    //         msg.setPushTime(new Date().toString());
    //         noticeMsgMapper.insert(msg);
    //         eventDividePlan.getRoutes().forEach(route -> {
    //             CDNoticeMsgRoute noticeMsgRoute = new CDNoticeMsgRoute();
    //             noticeMsgRoute.setId(route.getId());
    //             noticeMsgRoute.setNoticeId(msg.getNoticeId());
    //             noticeMsgRoute.setPathName(route.getPathName());
    //             noticeMsgRoute.setMileage(route.getMileage());
    //             noticeMsgRouteMapper.insert(noticeMsgRoute);
    //         });
    //         List<String> userList = eventDividePlan.getUserIds();
    //         if (!userList.isEmpty()) {
    //             userList.forEach(userId -> {
    //                 CDNoticeMsgUser noticeMsgUser = new CDNoticeMsgUser();
    //                 noticeMsgUser.setNoticeId(msg.getNoticeId());
    //                 noticeMsgUser.setUserId(userId);
    //                 noticeMsgUser.setState(0);
    //                 noticeMsgUser.setNoticeType("3");
    //                 noticeMsgUserMapper.insert(noticeMsgUser);
    //             });
    //         }
    //         ack.acknowledge();
    //     } catch (Exception e) {
    //         // 添加适当的异常处理
    //         System.err.println("Error processing newevent message: " + e.getMessage());
    //         // 根据业务需求决定是否ack或采取其他措施
    //     }
    // }

    /**
     * 4.5事件处置联动大屏通知
     *
     * @param message
     * @param ack
     */
    @KafkaListener(topics = "eventscreennotice")
    public void eventscreennotice(@Payload String message, Acknowledgment ack) {
        // 事件处置联动大屏通知
        try {
            log.info("4.5事件处置联动大屏通知接口消息: " + message);
            EventScreenNotice eventScreenNotice = JSON.parseObject(message, EventScreenNotice.class);
            // 根据事件ID查询事件列表接口获取事件信息
            GetEventListParam param = new GetEventListParam();
            param.setPage(1);
            param.setPageSize(10);
            param.setEventId(eventScreenNotice.getEventId());
            JsonNode eventList = growUpApiService.getEventList(param, eventScreenNotice.getUserId());
            if (eventList.get("totalCount").asInt() > 0) {
                JsonNode jsonNode = eventList.get("datas").get(0);
                EventEfficiency eventEfficiency = JSON.parseObject(jsonNode.toString(), EventEfficiency.class);
                // 坐标转换
                if (eventEfficiency.getLatitude() != null && eventEfficiency.getLongitude() != null && eventEfficiency.getLatitude() != 0 && eventEfficiency.getLongitude() != 0) {
                    double[] calWGS84toBD09 = GpsCoordinateUtils.calWGS84toBD09(eventEfficiency.getLatitude(), eventEfficiency.getLongitude());
                    eventEfficiency.setLatitude(calWGS84toBD09[0]);
                    eventEfficiency.setLongitude(calWGS84toBD09[1]);
                }
                // socket推送消息给大屏
                IMSystemMessage<EventEfficiency> sendMessage = new IMSystemMessage<>();
                sendMessage.setRecvIds(List.of(eventScreenNotice.getUserId()));
                // sendMessage.setRecvIds(List.of("1945296138008842241"));
                sendMessage.setData(eventEfficiency);
                sendMessage.setSendResult(false);
                sendMessage.setRecvTerminals(Collections.singletonList(IMTerminalType.LARGE_PC.code()));
                imClient.sendSystemMessage(sendMessage);
                log.info("发送4.5事件处置联动大屏通知，接收id:{}，内容:{}", eventScreenNotice.getUserId(), jsonNode);
            }
            ack.acknowledge();
        } catch (Exception e) {
            // 添加适当的异常处理
            log.error("4.5事件处置联动大屏通知接口失败 " + e.getMessage());
            // 根据业务需求决定是否ack或采取其他措施
        }
    }


    // /**
    //  * 4.6自定义发布变动通知
    //  *
    //  * @param message
    //  * @param ack
    //  */
    // @KafkaListener(topics = "publishapprovechange", groupId = "my-group")
    // public void publishapprovechange(@Payload String message, Acknowledgment ack) {
    //     // 自定义发布变动通知
    //     try {
    //         System.out.println("Received new event notification: " + message);
    //         PublishApproveChange approveChange = JSON.parseObject(message, PublishApproveChange.class);
    //         // 这里添加您的业务逻辑，如通知APP用户等
    //         ack.acknowledge();
    //     } catch (Exception e) {
    //         // 添加适当的异常处理
    //         System.err.println("Error processing newevent message: " + e.getMessage());
    //         // 根据业务需求决定是否ack或采取其他措施
    //     }
    // }
}
